import { _decorator, Component, Layers, Node, resources, Sprite, SpriteFrame, UITransform } from 'cc'
const { ccclass, property } = _decorator
import { TileManage } from './TileManage'
import { createUINode, randomByRange } from '../../Utils'
import DataManage from '../../Runtime/dataManage'
import ResourceManage from '../../Runtime/resourceManage'

export const TILE_WIDTH = 55
export const TILE_HEIGHT = 55

@ccclass('TileMapManage')
export class TileMapManage extends Component {
  // 初始化地图
  async init() {
    const { mapInfo } = DataManage.Instance
    DataManage.Instance.tileInfo = []
    // 加载图片资源
    const spriteFrames = await ResourceManage.Instance.loadDir('texture/tile', SpriteFrame)

    // 遍历地图二维数组
    for (let i = 0; i < mapInfo.length; i++) {
      let column = mapInfo[i]
      DataManage.Instance.tileInfo[i] = []
      // 遍历每一列
      for (let j = 0; j < column.length; j++) {
        let item = column[j]
        // 因为有的瓦片是空的，所以这里需要判断
        if (!item.src || !item.type) {
          // 这种空白格子不做任何渲染
          continue
        }

        // 创建一个瓦片节点
        const node = createUINode()
        // 这里定义精灵图片名称
        // 因为 1-4 5-8 9-12 都是一个方向不同样式的瓦片，所以这里可以进行随机获取，让每次这一个瓦片用的图片不一样
        // 为了减少随机的数量，免得瓦片出现太多重复，所以这里只对偶数位置瓦片进行随机
        let number = item.src
        if ((number == 1 || number == 5 || number == 9) && i % 2 == 0 && j % 2 == 0) {
          number = randomByRange(number, number + 4)
        }
        const imgSrc = `tile (${number})`
        // 设置精灵图的图片
        const spriteFrame = spriteFrames.find(v => v.name === imgSrc)
        const tileManage = node.addComponent(TileManage)
        DataManage.Instance.tileInfo[i][j] = tileManage
        const type = item.type
        tileManage.init(type, spriteFrame, i, j)
        // 添加父节点
        node.setParent(this.node)
      }
    }
  }
}
